﻿//文档就绪函数
$(function () {
    //初始化表格
    ShowWWHours();
});

var token = localStorage.getItem("token");

//工人工时列表展示
function ShowWWHours() {
    layui.use(function () {
        var table = layui.table;
        var WorkerNumber = $("#WorkerNumber").val();
        var Status = $("#Status").val();

        // 点击导出按钮
        document.getElementById('exportBtn').addEventListener('click', function () {
            var checkStatus = table.checkStatus('WWHoursTable');  // 获取当前表格的选中状态
            var selectedData = checkStatus.data;  // 获取选中的数据
            if (selectedData.length === 0) {
                alert('请先选择要导出的数据!');
                return;
            }
            var filteredData = selectedData.map(function (item) {
                // 创建一个新对象，只包含您想要的属性
                return {
                    '工人工时Id': item.wwHoursId,
                    '工人编号': item.workerNumber,
                    '工人姓名': item.workersName,
                    '手机号码': item.phoneNumber,
                    '所属部门': item.department,
                    '工作时长': item.workingHours,
                    '休息时长': item.restDuration,
                    '状态': item.status,
                };
            });
            console.log(filteredData);

            // 使用 XLSX 导出选中的数据
            var wb = XLSX.utils.book_new();
            var ws = XLSX.utils.json_to_sheet(filteredData); // 将选中的数据转换为工作表
            XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

            // 导出为 Excel 文件
            XLSX.writeFile(wb, '工人工时列表.xlsx');
        });

        //执行渲染
        table.render({
            elem: '#WWHoursTable',
            page: {
                limit: 15, //每页显示的条数
                limits: [15, 20, 25, 30] //每页显示条数的选择项
            },
            cols: [[
                { type: 'checkbox', fixed: 'left' },
                { field: 'workerNumber', title: '工人编号', width: 130 },
                { field: 'workersName', title: '工人姓名', width: 130 },
                { field: 'phoneNumber', title: '手机号码', width: 130 },       
                {
                    field: 'workingHours', title: '工作时长', width: 130,
                    templet: function (d) {
                        return d.workingHours + '个小时';
                    }
                },
                { field: 'department', title: '所属部门', width: 130 },
                {
                    field: 'restDuration', title: '休息时长', width: 130,
                    templet: function (d) {
                        return d.restDuration + '个小时';
                    }
                },
                {
                    field: 'status', title: '状态', width: 130,
                    templet: function (d) {
                        // 根据状态返回不同颜色的字体
                        var statusColor = '';
                        switch (d.status) {
                            case '上工':
                                statusColor = 'style="color: #16b777;"';
                                break;
                            case '请假':
                                statusColor = 'style="color: #ffb800;"';
                                break;
                            case '旷工':
                                statusColor = 'style="color: #ff5722;"';
                                break;
                            default:
                                // 如果状态不是上述任何一个，可以使用默认颜色或不做特殊处理
                                statusColor = '';
                        }
                        // 返回带有样式的状态文本
                        return '<span ' + statusColor + '>' + d.status + '</span>';
                    }
                },
                {
                    field: '', title: '操作', width: 180, templet: function (d) {

                        return '<a class="layui-btn layui-bg-blue layui-btn-xs" onclick="EditWWHours(' + d.wwHoursId + ')">编辑</a>' +
                            '<a class="layui-btn layui-bg-blue layui-btn-xs" onclick="CheckInfo(' + d.wwHoursId + ')">查看</a>' +
                            '<a class="layui-btn layui-bg-red layui-btn-xs" layui-bg-red onclick="DeleteWWHours(' + d.wwHoursId + ')">删除</a>';
                    },
                }
            ]],
            //数据接口
            data: []
        });
        //请求数据
        $.ajax({
            url: '../WWHours/GetWWHoursList',
            type: "get",
            headers: {
                "Authorization": localStorage.getItem("token")
            },
            data: {
                PageIndex: 1,
                PageSize: 15,
                WorkerNumber: WorkerNumber,
                Status: Status
            },
            success: function (data) {
                data = JSON.parse(data);
                console.log(data);
                table.reload('WWHoursTable', {
                    pagge: {
                        limit: 15,
                        limits: [15, 20, 25, 30]
                    },
                    data: data.data.list
                });
            },
            error: function () {
                console.log("请求失败");
            }

        });
    })
}

var obj = {
    WorkerListId: '',
    WorkerNumber: '',
    WorkersName: '',
    PhoneNumber: '',
    Gender: '',
    Department: '',
    TeamsAndGroups: '',
    Status: ''
};

//添加工人工时
window.AddWWorkingHours = function AddWWorkingHours() {
    layui.use(['layer', 'form'], function () {
        var layer = layui.layer;
        var form = layui.form;
        layer.open({
            type: 1,
            title: '添加工人信息',
            shadeClose: true,
            shade: 0.8,
            area: ['800px', '500px'],
            maxmin: true, // 允许全屏最小化
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: `<form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">工人编号</label>
                    <div class="layui-input-inline">
                        <input type="text" id="WorkerNumber" name="WorkerNumber" required lay-verify="required" placeholder="请输入工人编号" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">工人名称</label>
                    <div class="layui-input-block">
                        <input type="text" id="WorkersName" name="WorkersName" required lay-verify="required" placeholder="请输入工人名称" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">所属部门</label>
                    <div class="layui-input-block">
                        <select name="Department" style="width:300px">
                            <option value="">请选择部门</option>
                            <option value="生产部">生产部</option>
                            <option value="销售部">销售部</option>
                            <option value="质检部">质检部</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">联系方式</label>
                    <div class="layui-input-block">
                        <input type="text" id="PhoneNumber" name="PhoneNumber" required lay-verify="required|phone" placeholder="请输入联系方式" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">工作时长</label>
                    <div class="layui-input-block">
                        <input type="text" id="WorkingHours" name="WorkingHours" required lay-verify="required" placeholder="请输入工作时长" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">休息时长</label>
                    <div class="layui-input-block">
                        <input type="text" id="RestDuration" name="RestDuration" required lay-verify="required" placeholder="请输入休息时长" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block" style="text-align:right">
                        <button type="reset" class="layui-btn layui-btn-primary">取消</button>
                        <button class="layui-btn layui-bg-blue" lay-filter="formDemo">添加</button>
                    </div>
                </div>
            </form>`,
            success: function (layero, index) { // 添加 index 参数

                // 确保DOM元素已完全加载后渲染表单
                setTimeout(function () {
                    form.render();
                }, 100); // 使用 setTimeout 延迟渲染，确保DOM完全加载

                // 监听提交
                form.on('submit(formDemo)', function (data) {
                    var field = data.field;
                    var objTwo = {
                        WorkerNumber: field.WorkerNumber,
                        WorkersName: field.WorkersName,
                        Department: field.Department,
                        PhoneNumber: field.PhoneNumber,
                        WorkingHours: field.WorkingHours,
                        RestDuration: field.RestDuration,
                        CreatedBy: "张三"
                    };

                    $.ajax({
                        url: '../WWHours/AddWWHoursInfo',
                        type: "Post",
                        headers: {
                            "Authorization": localStorage.getItem("token")
                        },
                        data: {
                            dto: objTwo
                        },
                        success: function (res) {
                            var response = JSON.parse(res);
                            if (response.code === 1) {
                                layer.alert("添加成功");
                                setTimeout(function () {
                                    location.reload();
                                }, 2000);
                            } else {
                                layer.msg('添加失败：' + response.message, { icon: 2 });
                            }
                        },
                        error: function () {
                            layer.msg('添加失败,请稍后重试', {
                                time: 2000,
                                icon: 2
                            });
                        }
                    });
                    return false;
                });
                // 添加取消按钮功能
                $(layero).find('.layui-btn-primary').on('click', function () {
                    layer.close(index);
                });
            }
        });
    });
}

//查看
layui.use(['table', 'form', 'layer'], function () {
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    //查看工人信息
    window.CheckInfo = function (wwHoursId) {
        var token = localStorage.getItem("token");
        var isLoading = false; // 添加加载状态标识

        layer.open({
            type: 1,//iframe层
            title: '编辑工人信息',
            shadeClose: true,  // 点击遮罩区域，关闭弹层
            shade: 0.8,//遮罩透明度
            area: ['600px', '500px'],//弹层大小
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: `<form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">工人编号</label>
                    <div class="layui-input-inline">
                        <input type="text" id="WorkerNumberFind" name="WorkerNumberFind" required lay-verify="required" placeholder="请输入工人编号" autocomplete="off" style="width:300px" class="layui-input" disabled>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">工人名称</label>
                    <div class="layui-input-block">
                        <input type="text" id="WorkersNameFind" name="WorkersNameFind" required lay-verify="required" placeholder="请输入工人名称" autocomplete="off" style="width:300px" class="layui-input" disabled>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">所属部门</label>
                    <div class="layui-input-block">
                        <select id="Department" name="Department" disabled>
                            <option value="">请选择部门</option>
                            <option value="生产部">生产部</option>
                            <option value="销售部">销售部</option>
                            <option value="质检部">质检部</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">联系方式</label>
                    <div class="layui-input-block">
                        <input type="text" id="PhoneNumber" name="PhoneNumber" required lay-verify="required|phone" placeholder="请输入联系方式" autocomplete="off" style="width:300px" class="layui-input" disabled>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">工作时长</label>
                    <div class="layui-input-block">
                        <input type="text" id="WorkingHours" name="WorkingHours" required lay-verify="required" placeholder="请输入工作时长" autocomplete="off" style="width:300px" class="layui-input" disabled>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">休息时长</label>
                    <div class="layui-input-block">
                        <input type="text" id="RestDuration" name="RestDuration" required lay-verify="required" placeholder="请输入休息时长" autocomplete="off" style="width:300px" class="layui-input" disabled>
                    </div>
                </div>
            </form>`,
            success: function () {
                setTimeout(function () {
                    form.render();
                    if (!isLoading) {
                        isLoading = true;
                        new Promise(function (resolve, reject) {
                            $.ajax({
                                type: "Get",
                                headers: {
                                    "Authorization": token
                                },
                                url: "../WWHours/ReverseWWHours",
                                data: { WwHoursId: wwHoursId },
                                success: function (res) {
                                    var data = JSON.parse(res).data;
                                    console.log(data);
                                    $("#WorkerNumberFind").val(data.workerNumber);
                                    $("#WorkersNameFind").val(data.workersName);
                                    // 对部门数据进行格式处理及属性操作
                                    var departmentValue = data.department.trim().toLowerCase();
                                    $("#Department").removeAttr('disabled');
                                    $("#Department").val(departmentValue);
                                    resolve();
                                },
                                error: function () {
                                    reject();
                                }
                            });
                        }).then(function () {
                            form.render('select');
                            $("#Department").attr('disabled', 'disabled');
                            $("#PhoneNumber").val(data.phoneNumber);
                            $("#WorkingHours").val(data.workingHours);
                            $("#RestDuration").val(data.restDuration);
                            isLoading = false;
                        });
                    }
                }, 100);
            }
        });
    }
});

//全局变量
//编辑工人工时信息
layui.use(['table', 'form', 'layer'], function () {
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    //编辑工人信息--反填+修改
    window.EditWWHours = function (wwHoursId) {
        var token = localStorage.getItem("token");
        //先根据id获取数据
        $.ajax({
            type: "Get",
            headers: {
                "Authorization": token
            },
            url: "../WWHours/ReverseWWHours",
            data: { WWHoursId: wwHoursId },
            success: function (res) {
                var data = JSON.parse(res).data;
                console.log(data);
                $("#WWHoursId").val(data.WWHoursId);
                $("#WorkerNumberEdit").val(data.workerNumber);
                $("#WorkersNameEdit").val(data.workersName);
                $("#Department").val(data.department);
                $("#PhoneNumber").val(data.phoneNumber);
                $("#WorkingHours").val(data.workingHours);
                $("#RestDuration").val(data.restDuration);
                //存储反填信息到 obj 对象
                obj = {
                    WWHoursId: data.workerListId,
                    WorkerNumberEdit: data.workerNumber,
                    WorkersNameEdit: data.workersName,
                    Department: data.department,
                    PhoneNumber: data.phoneNumber,
                    WorkingHours: data.workingHours,
                    RestDuration: data.restDuration,
                    Status: data.status,
                    CreatedBy: data.createdBy,
                    CreatedDate: data.createdDate,
                    UpdatedBy: data.updatedBy,
                    DeletedBy: data.deletedBy,
                    DeletedDate: data.deletedDate,
                    IsDeleted: data.isDeleted
                };
            }
        });
        layer.open({
            type: 1,//iframe层
            title: '编辑工人信息',
            shadeClose: true,  // 点击遮罩区域，关闭弹层
            shade: 0.8,//遮罩透明度
            area: ['600px', '500px'],//弹层大小
            anim: 0, // 0-6 的动画形式，-1 不开启
            content: `<form class="layui-form" action="">
                <div class="layui-form-item">
                    <label class="layui-form-label">工人编号</label>
                    <div class="layui-input-inline">
                        <input type="text" id="WorkerNumberEdit" name="WorkerNumberEdit" required lay-verify="required" placeholder="请输入工人编号" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">工人名称</label>
                    <div class="layui-input-block">
                        <input type="text" id="WorkersNameEdit" name="WorkersNameEdit" required lay-verify="required" placeholder="请输入工人名称" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">所属部门</label>
                    <div class="layui-input-block">
                        <select id="Department" name="Department">
                            <option value="">请选择部门</option>
                            <option value="生产部">生产部</option>
                            <option value="销售部">销售部</option>
                            <option value="质检部">质检部</option>
                        </select>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">联系方式</label>
                    <div class="layui-input-block">
                        <input type="text" id="PhoneNumber" name="PhoneNumber" required lay-verify="required|phone" placeholder="请输入联系方式" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">工作时长</label>
                    <div class="layui-input-block">
                        <input type="text" id="WorkingHours" name="WorkingHours" required lay-verify="required" placeholder="请输入工作时长" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">休息时长</label>
                    <div class="layui-input-block">
                        <input type="text" id="RestDuration" name="RestDuration" required lay-verify="required" placeholder="请输入休息时长" autocomplete="off" style="width:300px" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block" style="text-align:right">
                        <button type="reset" class="layui-btn layui-btn-primary">取消</button>
                        <button class="layui-btn" lay-submit lay-filter="demo-update">提交修改</button>
                    </div>
                </div>
            </form>`,
            success: function () {

                var objTwo = {
                    WWHoursId: '',
                    WorkerNumber: '',
                    WorkersName: '',
                    PhoneNumber: '', 
                    Department: '',
                    WorkingHours: '',
                    RestDuration: '',
                    Status:'',
                    CreatedBy: '',
                    CreatedDate: '',
                    UpdatedBy: '',
                    DeletedBy: '',
                    DeletedDate: '',
                    IsDeleted: false
                };
                // 确保DOM元素已完全加载后渲染表单
                setTimeout(function () {
                    form.render();
                }, 300); // 使用 setTimeout 延迟渲染，确保DOM完全加载
                //监听提交
                form.on('submit(demo-update)', function (data) {
                    //console.log(data.field);
                    var field = data.field;
                    console.log(field);
                    //修改数据
                    objTwo.WorkerListId = obj.WorkerListId;
                    objTwo.WorkerNumber = field.WorkerNumberEdit;
                    objTwo.WorkersName = field.WorkersNameEdit ;
                    objTwo.Department = field.Department;
                    objTwo.PhoneNumber = field.PhoneNumber;
                    objTwo.WorkingHours = field.WorkingHours;
                    objTwo.RestDuration = field.RestDuration;
                    objTwo.Status = field.Status;
                    objTwo.CreatedBy = obj.CreatedBy;
                    objTwo.CreatedDate = obj.CreatedDate;
                    objTwo.UpdatedBy = "张三";
                    objTwo.DeletedBy = obj.DeletedBy;
                    objTwo.DeletedDate = obj.DeletedDate;
                    objTwo.IsDeleted = obj.IsDeleted;
                    console.log(objTwo);
                    //发送请求
                    $.ajax({
                        url: '../WWHours/UpdateWWHours',
                        type: "Post",
                        headers: {
                            "Authorization": token
                        },
                        data: { objTwo },
                        success: function (res) {
                            console.log(res);
                            var res = JSON.parse(res);
                            if (res.code === 1) {
                                layer.alert("修改成功");
                                setTimeout(function () {
                                    location.reload();
                                }, 2000);
                            } else {
                                layer.msg('修改失败：' + res.message, { icon: 2 });
                            }
                        },
                        error: function () {
                            layer.msg('修改失败,请稍后重试', {
                                time: 2000,
                                icon: 2
                            });
                        }
                    });
                    //阻止表单跳转
                    return false;
                });
            }
        });
    }
});

//删除工人工时
window.DeleteWWHours = function (id) {
    var token = localStorage.getItem("token");
    var data = JSON.stringify({
        wwHoursId: id,
        deletedBy: "张三"
    })
    layer.confirm('确定要删除该数据吗？', function (index) {
        $.ajax({
            url: '../WWHours/DeleteWWHours',
            type: "Post",
            headers: {
                "Authorization": token
            },
            data: { data: data },
            success: function (res) {
                console.log(res);
                var res = JSON.parse(res);
                if (res.code === 1) {
                    layer.msg('删除成功', { icon: 1 });
                    ShowWWHours();
                } else {
                    layer.msg('删除失败', { icon: 2 });
                }
            },
            error: function () {
                layer.msg('删除失败,请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
}